package workorder

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/business/process"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/dao"
	entity2 "gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
	"time"
)

//********************************************
//Func  ：查询意见类型
//Method：GET
//Usage ：留言板页面-意见-下拉选择意见类型
//********************************************
func QueryAllOpinionTypes(c *gin.Context) {
	types := []*entity2.OpinionType{}
	type1 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_Species),
		Type: "品种类",
	}
	types = append(types, type1)

	type2 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_Business),
		Type: "业务类",
	}
	types = append(types, type2)

	type3 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_Technology),
		Type: "技术类",
	}
	types = append(types, type3)

	type4 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_CurbPlatform),
		Type: "场外平台类",
	}
	types = append(types, type4)
	type5 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_MarketService),
		Type: "市场服务类",
	}
	types = append(types, type5)
	type6 := &entity2.OpinionType{
		Id:   int(entity2.EOpinionType_Other),
		Type: "其它类",
	}
	types = append(types, type6)

	c.JSON(http.StatusOK, model.SuccessObject("操作成功", types))
}

//********************************************
//Func  ：查询所有工单类型
//Method：GET
//Usage ：留言板页面--选择留言类型：咨询、建议、投诉（目前为3类）
//********************************************
func QueryAllWorkerOrderTypes(c *gin.Context) {
	types := []*entity2.OpinionType{}
	type1 := &entity2.OpinionType{
		Id:   int(entity2.EWorkOrderType_Counsel),
		Type: "咨询",
	}
	types = append(types, type1)

	type2 := &entity2.OpinionType{
		Id:   int(entity2.EWorkOrderType_Advice),
		Type: "建议",
	}
	types = append(types, type2)
	type3 := &entity2.OpinionType{
		Id:   int(entity2.EWorkOrderType_Complaint),
		Type: "投诉",
	}
	types = append(types, type3)
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", types))
}

//********************************************
//Func  ：查询客户的所有工单，分页输出查询结果
//Method：GET
//Usage ：我的反馈
//********************************************
func QueryCustomerWorkerOrders(c *gin.Context) {
	//默认一页查询12条
	pageSize, err1 := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err1 != nil {
		global.Log.Error("QueryCustomersWorkerOrders input param pagesize error:", zap.Any("error", err1))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	page, err2 := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err2 != nil {
		global.Log.Error("QueryAllOperators input param page error:", zap.Any("error", err2))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}
	mobile := c.DefaultQuery("mobile", "")
	total, orders, err := dao.QueryWorkOrderList(page, pageSize, mobile, "", "")
	if err != nil {
		global.Log.Error("dao.QueryWorkOrderList error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.FailCustomer("查询失败", err))
		return
	}

	type WorkOrderList struct { //列表查询输出
		Total int64
		List  []*entity2.WorkOrder
	}
	output := &WorkOrderList{
		Total: total,
		List:  orders,
	}

	c.JSON(http.StatusOK, model.SuccessObject("操作成功", output))
	return
}

//********************************************
//Func  ：查询客户的所有工单，分页输出查询结果
//Method：GET
//Usage ：我的反馈
//********************************************
func QueryOperatorWorkerOrders(c *gin.Context) {
	//默认一页查询12条
	pageSize, err1 := strconv.Atoi(c.DefaultQuery("pageSize", "12"))
	if err1 != nil {
		global.Log.Error("QueryCustomersWorkerOrders input param pagesize error:", zap.Any("error", err1))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	page, err2 := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err2 != nil {
		global.Log.Error("QueryAllOperators input param page error:", zap.Any("error", err2))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	startDate := c.DefaultQuery("startDate", "")
	endDate := c.DefaultQuery("endDate", "")
	mobile := c.DefaultQuery("mobile", "")

	total, orders, err := dao.QueryWorkOrderList(page, pageSize, mobile, startDate, endDate)
	if err != nil {
		global.Log.Error("dao.QueryWorkOrderList error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.FailCustomer("查询失败", err))
		return
	}

	type WorkOrderList struct { //列表查询输出
		Total int64
		List  []*entity2.WorkOrder
	}
	output := &WorkOrderList{
		Total: total,
		List:  orders,
	}

	c.JSON(http.StatusOK, model.SuccessObject("操作成功", output))
	return
}

//********************************************
//Func  ：查询工单详情
//Method：GET
//Usage ：我的反馈
//********************************************
func QueryWorkerOrderDetail(c *gin.Context) {

	workOrderId, err := strconv.ParseInt(c.DefaultQuery("workOrderId", ""), 10, 64)
	if err != nil {
		global.Log.Error("QueryWorkerOrderDetail work order id is lost.")
		c.JSON(http.StatusOK, model.Fail("未指明工单"))
		return
	}

	detail, err := dao.QueryWorkOrderDetail(workOrderId)
	if err != nil {
		global.Log.Error("dao.QueryWorkOrderDetail error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.FailCustomer("查询失败", err))
		return
	}

	c.JSON(http.StatusOK, model.SuccessObject("操作成功", detail))
	return
}

//********************************************
//Func  ：添加工单/即新增留言
//Method：POST
//Usage ：我的反馈
//********************************************
func AddWorkerOrder(c *gin.Context) {
	var workorder entity2.WorkOrder

	workorder.Title = strings.TrimSpace(c.DefaultPostForm("title", "")) //标题
	if len(workorder.Title) <= 0 {
		global.Log.Error("AddWorkerOrder title is none.")
		c.JSON(http.StatusOK, model.Fail("标题不能为空"))
		return
	}
	workorder.Body = c.DefaultPostForm("body", "") //正文
	if len(workorder.Body) <= 0 {
		global.Log.Error("AddWorkerOrder body is none.")
		c.JSON(http.StatusOK, model.Fail("正文不能为空"))
		return
	}
	workorder.Telephone = c.DefaultPostForm("telephone", "") //联系电话
	if len(workorder.Telephone) <= 0 {
		global.Log.Error("AddWorkerOrder telphone is none.")
		c.JSON(http.StatusOK, model.Fail("联系电话不能为空"))
		return
	}

	opt, err := strconv.Atoi(c.DefaultPostForm("opinionType", "0"))
	if err == nil {
		workorder.OpinionType = entity2.EOpinionType(opt)
	}

	orderType, err := strconv.Atoi(c.DefaultPostForm("workOrderType", "0"))
	if err == nil {
		workorder.WorkOrderType = entity2.EWorkOrderType(orderType)
	}

	workorder.ShareOrNot, err = strconv.ParseBool(c.DefaultPostForm("shareOrNot", "false"))
	workorder.ChannelName = c.DefaultPostForm("channelName", "")
	workorder.Status = entity2.EWorkerOrderStatus_NEW
	workorder.CustomerId, err = strconv.ParseInt(c.DefaultPostForm("customerId", ""), 10, 64)
	workorder.CustomerMobile = c.DefaultPostForm("customerMobile", "")
	workorder.ChannelName = c.DefaultPostForm("channelName", "")

	//--------------------
	//根据工单查找匹配流程
	processList, err := process.SearchProcessByOrderType(workorder.WorkOrderType)
	if len(processList) > 0 {
		workorder.CurProcessId = processList[0].ProcessId

		//分析一下可以选择的step
		stepListStr := processList[0].StepIds
		stepList := process.IdListStringToInt64(stepListStr)
		global.Log.Info("stepList.", zap.Any("stepList", stepList))
	}
	//--------------------
	neworder, err := dao.InsertWorkOrder(workorder)
	if err != nil {
		global.Log.Error("AddWorkerOrder failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("添加工单失败"))
	} else {
		c.JSON(http.StatusOK, model.SuccessObject("操作成功", neworder))
		global.Log.Info("AddWorkerOrder success.", zap.Any("new order", neworder))
	}
}

func QueryOpinionTypes(c *gin.Context) {
	types := []*entity2.OpinionType{}
	type1 := &entity2.OpinionType{
		Id:   0,
		Type: "意见类型1",
	}
	types = append(types, type1)

	type2 := &entity2.OpinionType{
		Id:   1,
		Type: "意见类型2",
	}
	types = append(types, type2)

	type3 := &entity2.OpinionType{
		Id:   2,
		Type: "意见类型3",
	}
	types = append(types, type3)

	type4 := &entity2.OpinionType{
		Id:   3,
		Type: "意见类型4",
	}
	types = append(types, type4)
}

//********************************************
//Func   工单答复，写入答复内容，并触发流转记录新增，
//Method：POST
//Usage ：如果status为NEW，则说明是直接回复
//           status为
//********************************************
func WorkOrderReply(c *gin.Context) {
	var order entity2.WorkOrder
	var err error
	order.Id, err = strconv.ParseInt(c.DefaultQuery("workOrderId", ""), 10, 64)
	if err != nil {
		global.Log.Error("WorkOrderReply work order id is lost.")
		c.JSON(http.StatusOK, model.Fail("未指明工单"))
		return
	}
	order.Reply = c.DefaultQuery("reply", "")
	if len(strings.TrimSpace(order.Reply)) <= 0 {
		global.Log.Error("WorkOrderReply reply is none.")
		c.JSON(http.StatusOK, model.Fail("回复不能为空"))
		return
	}

	//查找下一步Step
	order.CurStepId, err = strconv.ParseInt(c.DefaultQuery("stepId", ""), 10, 64)
	if err != nil {
		global.Log.Info("step id is lost.")
		order.CurStepId = 0
	}

	order.Status = entity2.EWorkerOrderStatus_APPLYRELEASE //entity.EWorkerOrderStatus_FINISH
	order.FinishAt = time.Now()
	err = dao.UpdateWorkOrder(order, "status,reply,finish_at")

	//写入flow记录
	flow, err := InsertFlowFunc(order.Id, order.CurProcessId, order.CurStepId, 0, order.Status)
	if err != nil {
		global.Log.Error("InsertFlowFunc failed.", zap.Any("error", err))
	}
	global.Log.Info("WorkOrderReply reply.", zap.Any("flow", flow))
}
